package it.koutifaris.travianmap.mapsqlparser;

import org.apache.commons.lang3.StringUtils;

class EntryBuilder {

	private static final int EXPECTED_VALUES = 10;
	private MapSqlEntry entry;
	private int index;

	EntryBuilder() {
		clear();
	}

	void clear() {
		entry = new MapSqlEntry();
		index = 0;
	}

	EntryBuilder addValue(String value) throws BuildException {
		switch (index) {
		case 0:
			entry.setId(parseInt(value));
			break;
		case 1:
			entry.setX(parseInt(value));
			break;
		case 2:
			entry.setY(parseInt(value));
			break;
		case 3:
			entry.setTribeId(parseInt(value));
			break;
		case 4:
			entry.setVillageId(parseInt(value));
			break;
		case 5:
			entry.setVillageName(parseString(value));
			break;
		case 6:
			entry.setPlayerId(parseInt(value));
			break;
		case 7:
			entry.setPlayerName(parseString(value));
			break;
		case 8:
			entry.setAllianceId(parseInt(value));
			break;
		case 9:
			entry.setAllianceName(parseString(value));
			break;
		case 10:
			entry.setVillagePopulation(parseInt(value));
			break;

		default:
			throw new BuildException("Too many values added! Expected " + EXPECTED_VALUES + " values.");
		}

		index++;
		return this;
	}

	MapSqlEntry build() throws BuildException {
		int numAdded = index - 1;
		if (numAdded != EXPECTED_VALUES) {
			throw new BuildException("Expected " + EXPECTED_VALUES + " values, but added " + numAdded);
		}

		return entry;
	}

	private int parseInt(String value) {
		return Integer.parseInt(value);
	}

	private String parseString(String value) {
		return StringUtils.replace(value, "&#39;", "'");
	}

	static class BuildException extends Exception {
		private static final long serialVersionUID = -8909620020273776188L;

		public BuildException(String message) {
			super(message);
		}
	}
}
